<!--
 * @Author: zhangjingyu
 * @Date: 2021-04-08 09:49:16
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-05-19 10:22:49
 * @FilePath: \vprisk10.14\src\views\ftpManage\pricingManage\hisBusiRepricing\hisRepricing_index.vue
 * @Description: 历史业务重定价主页面
-->
<template>
  <div>
      <!-- 历史业务重定价主页面 -->
    <div v-show="currentPage === 'index'">
      <upper-template
        @search="(searchForm.page = 1), searchFunc()"
        @clear="clearSearch"
      >
        <!-- 操作按钮区 -->
        <template slot="buttonArea">
          <el-button @click="addOrEditFunc('1')">新增</el-button>
          <el-button @click="addOrEditFunc('2')">编辑</el-button>
          <el-button @click="deleFunc()">删除</el-button>
          <el-button @click="addOrEditFunc('3')">复制</el-button>
          <el-button @click="toSiftForm()">筛选数据</el-button>
          <el-button @click="toViewData()">查看筛选数据</el-button>
          <el-button @click="toExcute()">执行定价</el-button>
          <el-button @click="toMonitor()">执行监控</el-button>
          <el-button @click="refFunc()">执行记录</el-button>
        </template>
        <!-- 搜索区 -->
        <template slot="searchArea">
          <el-form
            :model="searchForm"
            ref="searchForm"
            label-width="100px"
            label-position="left"
            size="mini"
          >
            <el-form-item label="重定价编号：">
              <el-input
                v-model="searchForm.taskCode"
                style="width:150px"
              ></el-input>
            </el-form-item>
            <el-form-item label="开始日期：" prop="taskSd">
              <auto-form
                v-model="searchForm.taskSd"
                elementType="3"
                style="width:150px"
              ></auto-form>
            </el-form-item>
          </el-form>
        </template>
        <!-- 显示隐藏区 -->
        <template slot="columnHide">
          <el-checkbox-group v-model="checkList">
            <el-checkbox
              v-for="item in textData"
              :label="item.label"
              :key="item.id"
              :disabled="item.hideDisable"
              >{{ item.label }}</el-checkbox
            >
          </el-checkbox-group>
        </template>
      </upper-template>
      <el-table
        ref="multipleTable"
        :data="tableData"
        @row-click="multipleTableClick"
      >
        <el-table-column
          width="55"
          type="selection"
          
        ></el-table-column>
        <el-table-column
          label="编码"
          prop="taskCode"
          v-if="tablePick[0]"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="名称"
          prop="taskName"
          v-if="tablePick[1]"
          :show-overflow-tooltip="true"
        ></el-table-column>
         <el-table-column
          label="开始日期"
          prop="taskSd"
          v-if="tablePick[2]"
          :show-overflow-tooltip="true"
        ></el-table-column>
         <el-table-column
          label="结束日期"
          prop="taskEd"
          v-if="tablePick[3]"
          :show-overflow-tooltip="true"
        ></el-table-column>
         <el-table-column
          label="记录数"
          prop="dataCount"
          v-if="tablePick[4]"
          :show-overflow-tooltip="true"
        ></el-table-column>
         <el-table-column
          label="开始时间"
          prop="startTime"
          v-if="tablePick[5]"
          :show-overflow-tooltip="true"
        ></el-table-column>
         <el-table-column
          label="结束时间"
          prop="startTime"
          v-if="tablePick[6]"
          :show-overflow-tooltip="true"
        ></el-table-column>
         <el-table-column
          label="状态"
          prop="status"
          v-if="tablePick[7]"
          :formatter="row=>$getLabel(row.status,statusList)"
          :show-overflow-tooltip="true"
        ></el-table-column>
      </el-table>
      <!-- 主表分页 -->
      <pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="searchForm.page"
        :page-size="searchForm.size"
        :pager-count="7"
        @refresh="searchFunc"
        :total="total"
      ></pagination>
      <!-- 新增,编辑 复制保单-->
      <el-dialog
        v-dialogDrag
        :title="titleName"
        :visible.sync="addOrEdit"
        width="514px"
      >
        <el-form
          :model="saveForm"
          ref="saveForm"
          label-width="110px"
          label-position="left"
          :rules="saveFormRules"
        >
          <el-form-item label="重定价编号：" prop="taskCode">
            <el-input
              v-model="saveForm.taskCode"
              maxlength="40"
              placeholder="REPRI_"
              :disabled="operateType == 2"
            ></el-input>
          </el-form-item>
          <el-form-item label="重定价名称：" prop="taskName">
            <el-input v-model="saveForm.taskName" maxlength="40"></el-input>
          </el-form-item>
          <el-form-item label="重定价开始日期: " prop="taskSd">
            <el-date-picker
              v-model="saveForm.taskSd"
              style="width:100%"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
            ></el-date-picker>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="saveFunc(operateType)">保 存</el-button>
          <el-button @click="formDataFilter" :disabled="!saved"
            >数据筛选</el-button
          >
          <el-button @click="addOrEdit = false">取 消</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 数据筛选页面 -->
    <data-filter
      v-if="currentPage === 'dataFilter'"
      @backIndex="backIndex"
      @toFilterData="toFilterData"
      :code="toRowObj.taskCode"
    ></data-filter>
    <!-- 查看筛选数据页面 -->
    <view-filter-data
      v-if="currentPage === 'viewData'"
      :baseData="toRowObj"
      @backIndex="backIndex"
      @toDataFilter="viewToFilter"
    ></view-filter-data>
    <!-- 重定价任务监控页面 -->
    <monitor 
      v-if="currentPage === 'monitor'"
      :baseData="toRowObj"
      @backIndex="backIndex"
      @toDataFilter="viewToFilter"
      @toSubTasks = "toSubTasks"
      @toResult = "toResult"
    ></monitor>
    <!-- 执行记录 -->
    <execute-notes
     v-if="currentPage === 'executeNotes'"
      :baseData="toRowObj"
      @backIndex="backIndex"
      @toSubTasks ="toSubTasks"
    ></execute-notes>
    <!-- 子任务 -->
    <sub-tasks
     v-if="currentPage === 'subTasks'"
      :baseData="toRowObj"
      @backIndex="backIndex"
      @toEngine="toEngine"
      @backExecuteNotes = 'currentPage = "executeNotes"'
    ></sub-tasks>
    <!-- 引擎任务 -->
    <engine-tasks
     v-if="currentPage === 'engineTasks'"
      :baseData="toRowObj"
      @backIndex="backIndex"
      @backSubTasks="currentPage = 'subTasks'"
      @backExecuteNotes = 'currentPage = "executeNotes"'
      @toResult = "toResult"
    ></engine-tasks>
    <!-- 查看结果 -->
    <task-result
     v-if="currentPage === 'taskResult'"
      :baseData="toRowObj"
      :comefrom = "comefrom"
      @toBackLast="toBackLast"
    ></task-result>
  </div>
</template>

<script>
import { pricingTask } from "@/api/index";
import autoForm from "@/components/ftp/autoForm.vue";
import dataFilter from "./rp_dataFilter";
import viewFilterData from "./rp_viewFilterData";
import monitor from "./rp_monitor";
import executeNotes from "./rp_executeNotes";
import subTasks from "./rp_subTasks";
import engineTasks from "./rp_engineTasks";
import taskResult from "./rp_taskResult";
import moment from "moment"
export default {
  components: { autoForm,dataFilter,viewFilterData,monitor,executeNotes,subTasks,engineTasks,taskResult },
  data() {
    return {
      currentPage:'index',
      comefrom :"",
      searchForm: {
        taskCode: "",
        taskSd: "",
        page: 1,
        size: 15
      },
      total: 0,
      operateType: "1",
      saveForm: {
        taskCode: "REPRI_",
        taskName: "",
        taskSd: ""
      },
       // 传入其他页面的数据
      toRowObj: {},
      statusList:[],
      saveFormRules: {
        taskCode: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          {
            pattern: /^REPRI_[0-9a-zA-Z_]{1,35}$/,
            message:
              "只可输入40位英文字母、数字和下划线，注：必须以'REPRI_'开头",
            trigger: "blur"
          },
          { validator: this.taskCodeValid, trigger: "blur" }
        ],
        taskName: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          {
            pattern: /^[\u4E00-\u9FA5A-Za-z0-9（）()\[\]【】{}]{1,40}$/,
            message: "只能输入1-40位的汉字、字母、数字或括号",
            trigger: "blur"
          }
        ],
        taskSd: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          { validator: this.taskSdValid, trigger: "blur" }
        ]
      },
      addOrEdit: false,
      saved: false, // 当前数据是否已保存标识
      // 主表列显示隐藏依据
      textData: [
        { id: "1", label: "编号", hideDisable: true },
        { id: "2", label: "名称", hideDisable: true },
        { id: "3", label: "开始日期" },
        { id: "4", label: "结束日期" },
        { id: "5", label: "记录数" },
        { id: "6", label: "开始时间" },
        { id: "7", label: "结束时间" },
        { id: "8", label: "状态" }
      ],
      checkList: [
        "编号",
        "名称",
        "开始日期",
        "结束日期",
        "记录数",
        "开始时间",
        "结束时间",
        "状态"
      ],
      // 主表数据
      tableData: []
    };
  },
  computed: {
    tablePick() {
      return this.$tableDataPick(this.checkList, this.textData);
    },
    titleName() {
      let arr = [
        "新增历史业务重定价信息",
        "编辑历史业务重定价信息",
        "复制历史业务重定价信息"
      ];
      return arr[this.operateType - 1];
    }
  },
  created() {
    this.searchFunc();
    this.getDict();
  },
  methods: {
    getDict(){
      // 获取定价状态 
      this.$getDict('ftp_pricing_task_status').then(res=>{
        if(res.code==200){
          this.statusList = res.datas;
        }
      })
    },
    taskCodeValid(rule, value, callback) {
      if (this.operateType == "1" || this.operateType == "3") {
        pricingTask
          .repricingTaskCheckTaskCodeUnique(`"${value}"` )
          .then(res => {
            if (res.data == '0') {
              callback();
            } else {
              callback(new Error("编号校验不通过"));
            }
          });
      } else {
        callback();
      }
    },
    taskSdValid(rule, value, callback) {
      pricingTask.repricingTaskCheckTaskSd(`"${value}"`).then(res => {
        if (res.data == '1') {
          callback();
        } else {
          callback(new Error("日期校验不通过"));
        }
      });
    },
    searchFunc() {
      let data = this.searchForm;
      pricingTask.repricingTaskFindAll(data).then(res => {
        if (res.code == 200) {
          this.tableData =res.rows.map(v=>{
            let obj = v;
            obj.taskEd =obj.taskEd? moment(obj.taskEd).format('yyyy-MM-DD'):"-"
            obj.taskSd = obj.taskSd?moment(obj.taskSd).format('yyyy-MM-DD'):"-"
            return obj;
          });
          this.total = res.total;
        }
      });
    },
    clearSearch() {
      (this.searchForm.taskCode = ""),
        (this.searchForm.taskSd = ""),
        (this.searchForm.page = 1);
    },
    addOrEditFunc(val) {
       if (this.$refs.saveForm) {
          this.$refs.saveForm.resetFields();
      }
      this.saved = false;
      this.operateType = val;
      if (val == "1") {
        for (let key in this.saveForm) {
          this.saveForm[key] = ''
        }
        this.saveForm.taskCode = "REPRI_";
      }
      if (val == "2") {
         this.saved = true;
        let selection = this.$refs.multipleTable.selection
        if(selection.length!=1){return this.$message.warning('请选择一条数据')}
        let row = selection[0]
        this.saveForm.taskCode = row.taskCode
        this.saveForm.taskSd = row.taskSd
        this.saveForm.taskName = row.taskName
      }
      if (val == "3") {
         let selection = this.$refs.multipleTable.selection
        if(selection.length!=1){return this.$message.warning('请选择一条数据')}
         let row = selection[0]
        this.saveForm.taskCode = row.taskCode
        this.saveForm.taskSd = row.taskSd
        this.saveForm.taskName = row.taskName
      }
        this.addOrEdit = true;
    },
    saveFunc(operateType) {
      this.$refs["saveForm"].validate(valid => {
        if (valid) {
          let data = {
            ...this.saveForm
          };
          data.operateType = operateType;
          pricingTask.repricingTaskSave(data).then(res => {
            if (res.code == 200) {
              this.$message.success("保存成功");
               this.saved = true;
              this.searchFunc();
            }
          });
        }
      });
    },
    deleFunc() {
       let selection = this.$refs.multipleTable.selection;

      if (selection.length == 0) {
        return this.$message.warning("请选择数据");
      }
      let data = selection.map(v=>v.id);
      this.$confirm("你确定要删除选中的数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          pricingTask.repricingTaskRemove(data).then((res) => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              this.searchFunc();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    toExcute() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据");
      }
      pricingTask.repricingTaskExcute({
        taskCode:selection[0].taskCode,
        taskSd:selection[0].taskSd,
        taskEd:selection[0].taskEd}).then(res=>{
        if(res.code==200&&res.data=='1'){
          this.$message.success('重定价任务执行成功！')
        }else{
          this.$message.error(res.message)
        }
      })
    },
    toMonitor() {
       let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据");
      }
      let data = {
        taskCode: selection[0].taskCode
      };
      pricingTask.toMonitorRepricing(data).then((res) => {
        if (res.code == 200) {
          this.toRowObj = {...selection[0]}
          if(!res.data.pricingRecord)return this.$message.error('监控页面数据查询为空')
           this.toRowObj .pricingCode = res.data.pricingRecord.pricingCode
          this.currentPage = 'monitor';
        }
      });
    },
    //执行记录
    refFunc() {
       let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据");
      }
       let row = selection[0];
       this.toRowObj = {...row};
          this.currentPage = 'executeNotes';

    },
    // 主页面重定价数据筛选
    toSiftForm() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据");
      }
      let row = selection[0];
       this.toRowObj = {...row};
      this.currentPage = "dataFilter";
    },
    // 数据筛选to查看筛选数据
    toFilterData(val) {
      this.currentPage = "viewData";
      this.toRowObj.positionList = val;
    },
    // 数据筛选查看 to 数据筛选
    viewToFilter() {
      this.currentPage = "dataFilter";
    },
    // 跳转到子任务页面
    toSubTasks(obj){
      console.log(obj)
      this.toRowObj = obj
      this.currentPage = "subTasks"
    },
    // 跳转至引擎任务
    toEngine(){
      this.currentPage = "engineTasks"

    },
    toBackLast(){
      this.currentPage = this.comefrom
    },
    // 跳转到查看结果
    toResult(val){
      console.log(val,'val')
      this.toRowObj.pricingCode = val.pricingCode
      this.comefrom = this.currentPage
      this.currentPage = "taskResult"
    },
    // 返回主页面事件处理
    backIndex(v) {
      this.currentPage = "index";
    },
    toViewData() {
       let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据");
      }
      let row = selection[0];
      this.toRowObj = {...row};
      this.currentPage = "viewData";
    },
    multipleTableClick(row) {
      this.$refs.multipleTable.clearSelection();
      this.$refs.multipleTable.toggleRowSelection(row, true);
    },
    // 表单底部的数据筛选按钮
    formDataFilter() {
       this.toRowObj = {
        ...this.saveForm
        }
      this.currentPage = "dataFilter";
      this.addOrEdit = false;
    },
    handleSizeChange(val) {
      this.searchForm.size = val;
      this.searchFunc();
    },
    handleCurrentChange(val) {
      this.searchForm.page = val;
      this.searchFunc();
    }
  }
};
</script>

<style lang="scss" scoped>
/deep/ .formTitle {
  font-size: 14px;
  font-weight: 700;
  display: block;
  margin-bottom: 10px;
}
</style>